package com.tsoft.wihouse;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Selectable;

import java.util.List;

/**
 * 安居客租房信息爬虫
 * @author Tan Yuanpeng E-mail:tony.jingzhou@gmail.com
 * @version 创建时间：2018/2/27 23:15
 */
public class AnjukePageProcessor implements PageProcessor {


    public static final String URL_POST = "https://bj\\.zu\\.anjuke\\.com/rent/\\w+";

    public static final String URL_LIST = "https://bj\\.zu\\.anjuke\\.com/ditie/\\w*-*\\w*-*\\w*";

    private Site site = Site.me()
            .setRetryTimes(3)
            .setSleepTime(1000)
            .setUserAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31");;


    public void process(Page page) {

        if (page.getUrl().regex(URL_LIST).match()) {
            List<String> details = page.getHtml().css("div.zu-itemmod").links().regex(URL_POST).all();
            page.addTargetRequests(details);
            List<String> pages = page.getHtml().css("div.multi-page").links().regex(URL_LIST).all();
            page.addTargetRequests(pages);
        }else{
            page.putField("url",page.getUrl());
            page.putField("title", page.getHtml().xpath("//div[@class='tit cf']/h3/text()"));
            List<Selectable> nodes = page.getHtml().css("dl.p_phrase").nodes();
            for (Selectable node : nodes) {
                String title = node.xpath("dt/text()").get();
                String value = node.xpath("dd/text()").get();
                if (title.equals("租金")){
                    value = node.xpath("//span[@class='f26']/text()").get();
                }
                if (title.equals("所在小区")){
                    value = node.xpath("dd/a/text()").get();
                    String xqUrl = node.xpath("dd/a").links().get();
                    System.out.println("xqUrl---"+xqUrl);
                }
                System.out.println(title+"----"+value);
            }
        }
    }

    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {

        Spider.create(new AnjukePageProcessor())
                //从"https://github.com/code4craft"开始抓
                .addUrl("https://bj.zu.anjuke.com/ditie/dt8-l2-p1/")
                //开启5个线程抓取
                .thread(5)
                //启动爬虫
                .run();
    }



}
